import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { LockOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { changePassword } from '../api/user'; // 假设我们有这个API调用
import { RootState } from '../store';
import { useSelector } from 'react-redux';

const ChangePassword: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const user = useSelector((state: RootState) => state.auth.user);

  // 检查用户是否已登录
  if (!user || !user.id) {
    message.error('请先登录后再进行密码修改');
    navigate('/login'); // 跳转到登录页面
    return <div>加载中...</div>;
  }

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      // 确保 user.id 存在
      if (user && user.id !== undefined) {
        await changePassword(user.id, values);
        message.success('密码修改成功');
        navigate('/profile'); // 导航到个人信息页面
      } else {
        message.error('用户信息异常，请重新登录');
      }
    } catch (error) {
      message.error('密码修改失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '50vh' }}>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          name="oldPassword"
          label="旧密码"
          rules={[{ required: true, message: '请输入您的旧密码' }]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="旧密码" />
        </Form.Item>
        <Form.Item
          name="newPassword"
          label="新密码"
          rules={[
            { required: true, message: '请输入您的新密码' },
            { min: 6, message: '密码长度至少为6个字符' },
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="新密码" />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          label="确认新密码"
          dependencies={['newPassword']}
          hasFeedback
          rules={[
            { required: true, message: '请确认您的新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致!'));
              },
            }),
          ]}
        >
          <Input.Password prefix={<LockOutlined />} placeholder="确认新密码" />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" loading={loading}>
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default ChangePassword;